package com.zl.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zl.basic.constant.VerifyConstants;
import com.zl.basic.constant.WxConstants;
import com.zl.basic.exception.BusinessException;
import com.zl.basic.jwt.JwtUtils;
import com.zl.basic.jwt.LoginData;
import com.zl.basic.jwt.RsaUtils;
import com.zl.basic.service.impl.BaseServiceImpl;
import com.zl.basic.util.AjaxResult;
import com.zl.basic.util.HttpUtil;
import com.zl.basic.util.MD5Utils;
import com.zl.basic.util.StrUtils;
import com.zl.system.domain.Menu;
import com.zl.user.domain.LoginInfo;
import com.zl.user.domain.User;
import com.zl.user.domain.WXUser;
import com.zl.user.dto.LoginDto;
import com.zl.user.mapper.LoginInfoMapper;
import com.zl.user.mapper.UserMapper;
import com.zl.user.mapper.WXUserMapper;
import com.zl.user.service.LoginInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LoginInfoServiceImpl extends BaseServiceImpl<LoginInfo> implements  LoginInfoService {
    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WXUserMapper wxUserMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String, Object> loginAccount(LoginDto loginDto) {
        String account = loginDto.getAccount();
        String password = loginDto.getPassword();
        Integer loginType = loginDto.getLoginType();
        //空值校验
        if (StringUtils.isEmpty(account)||StringUtils.isEmpty(password)||
                StringUtils.isEmpty(loginType)){
            throw new BusinessException("数据不能为空");
        }
        //账号校验
        LoginInfo logininfo = loginInfoMapper.loadByAccount(loginDto);
        if (logininfo==null){
            throw new BusinessException("账号或密码错误");
        }

        //密码校验
        String md5 = MD5Utils.encrypByMd5(password + logininfo.getSalt());
        if (!md5.equals(logininfo.getPassword())){
            throw new BusinessException("账号或密码错误");
        }


        //启用禁用校验

        if(!logininfo.getDisable()){
            throw new BusinessException("你的账号被冻结，请联系管理员!!!");
        }

       /* // 生成key[token] 将key和登录对象信息存入redis中
        String token = UUID.randomUUID().toString();
        // 清空盐值和密码--安全
        logininfo.setPassword(null);
        logininfo.setSalt(null);

        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo",logininfo);*/

        Map<String,Object> map =  loginSuccessJwtHandler(logininfo);

        return map;
    }

    private Map<String, Object> loginSuccessJwtHandler(LoginInfo logininfo) {
        LoginData loginData = new LoginData();
        loginData.setLogininfo(logininfo);
        HashMap<String, Object> map = new HashMap<>();
        try {
            if (logininfo.getType()==0){
                List<String> permissions = loginInfoMapper.loadByPermissionByLoginInfoId(logininfo.getId());
                List<Menu> menus =loginInfoMapper.loadbByMenusByLogininfoId(logininfo.getId());
                loginData.setPermissions(permissions);
                loginData.setMenus(menus);
                map.put("permissions",permissions);
                map.put("menus",menus);
            }
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);
            map.put("token",jwtToken);
            map.put("logininfo",logininfo);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public AjaxResult loginWechat(String code) {

        String url = WxConstants.GET_ACK_URL
                .replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", code);

        String jsonStr = HttpUtil.httpGet(url);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        WXUser wxUser =  wxUserMapper.loadByOpenid(openid);
        if (wxUser!=null&&wxUser.getUser_id()!=null){
           LoginInfo logininfo =  loginInfoMapper.loadByUserId(wxUser.getUser_id());

         /*   // 生成key[token] 将key和登录对象信息存入redis中
            String token = UUID.randomUUID().toString();
            // 清空盐值和密码--安全
            logininfo.setPassword(null);
            logininfo.setSalt(null);

            redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",token);
            map.put("logininfo",logininfo);*/

            Map<String,Object> map =  loginSuccessJwtHandler(logininfo);
            return AjaxResult.me().setResultObj(map);
        }else{
            HashMap<String, Object> map = new HashMap<>();
            map.put("access_token",access_token);
            map.put("openid",openid);
            return AjaxResult.me().setSuccess(false).setResultObj(map);
        }

    }



    @Override
    public AjaxResult binderWechat(LoginDto loginDto) {
        String phone = loginDto.getPhone();
        String openId = loginDto.getOpenId();
        String verifyCode = loginDto.getVerifyCode();
        String accesstoken = loginDto.getAccessToken();
        //校验
        //1.校验 - 空置校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("数据不能为空");
        }

        //2.校验 - 验证码是否过期  //code:1215215155
        Object redisCode = redisTemplate.opsForValue().get(VerifyConstants.BINDER_PREFIX + phone);
        if(redisCode==null){
            throw new BusinessException("验证码过期");
        }
        //3.校验 - 验证码是否正确
        if(!redisCode.toString().split(":")[0].equalsIgnoreCase(verifyCode.trim())){
            throw new BusinessException("验证码错误");
        }


        //绑定用户：t_wxUser【user_id】 绑定 t_user
        //4.获取WxUser - 发送第三个请求 - json字符串
        String url = WxConstants.GET_USER_URL
                .replace("ACCESS_TOKEN",accesstoken)
                .replace("OPENID",openId);

        String jsonStr = HttpUtil.httpGet(url);
        WXUser wxuser = jsonStr2Wxuser(jsonStr); //user_id

        //5.通过phone查询User
        User user = userMapper.loadByPhone(phone);
        //5.1.如果没有 - 根据phone创建User对象 - 创建Logininfo对象 - 保存Logininfo对象 - 保存User对象
        if(user == null){
            user = phone2User(phone);
            LoginInfo logininfoTmp= user2Logininfo(user);

            loginInfoMapper.save(logininfoTmp);
            user.setLogininfo_id(logininfoTmp.getId());
            userMapper.save(user);
        }
        //6.将User对象的id设置到WxUser对象中
        wxuser.setUser_id(user.getId());
        //7.将WxUser对象添加到数据库
        wxUserMapper.save(wxuser);

        //8.做免密登录
        LoginInfo logininfo = loginInfoMapper.loadById(user.getLogininfo_id());
      /*  String token = UUID.randomUUID().toString();
        //去掉密码和盐值 - 安全
        logininfo.setPassword(null);
        logininfo.setSalt(null);


        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo",logininfo);*/

        Map<String,Object> map =  loginSuccessJwtHandler(logininfo);

        return AjaxResult.me().setResultObj(map);
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(token);
    }

    private LoginInfo user2Logininfo(User user) {
        LoginInfo logininfo = new LoginInfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        //随机的纯数据密码
        String randomPwd = StrUtils.getRandomString(6);
        String md5Pwd = MD5Utils.encrypByMd5(randomPwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private WXUser jsonStr2Wxuser(String jsonStr) {
        WXUser wxuser = new WXUser();
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setAddress(jsonObject.getString("country") + jsonObject.getString("province") + jsonObject.getString("city"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;
    }
}
